<?php
namespace control;

// 委外合同
class outsourceContractClass extends adIndexClass
{
    private const page = 'outsourceContract'; # 权限
    private const table = 'outsource_contract'; # 数据表
    private const tableMx = 'sales_contract_detail';//委外合同明细表
    private const tablePay = 'sales_contract_payback'; # 回款表
    private const title = '委外合同';
    private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'contractTrackSearch':
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'contract'  => [
                        'name'  => "合同编号",
                        'width' => 200,
                    ],
                    'supplier'         => [
                        'name'  => '委外单位',
                        'width' => 200,
                    ],
                    'code'         => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 70,
                    ],
                    'num'         => [
                        'name'  => '收货数量',
                        'width' => 100,
                    ],
                    'price'          => [
                        'name'  => '单价（' . static::$unit . '）',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '金额（' . static::$unit . '）',
                        'width' => 100,
                    ],
                    'rate'          => [
                        'name'  => '税率(%)',
                        'width' => 100,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额（' . static::$unit . '）',
                        'width' => 100,
                    ],
                    'moneyWithTax'          => [
                        'name'  => '价税合计（' . static::$unit . '）',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'signedDate'          => [
                        'name'  => '签订日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "合同编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "合同名称",
                        'width' => 250,
                    ],
                    'supplier'         => [
                        'name'  => '委外单位',
                        'width' => 250,
                    ],
                    'type'          => [
                        'name'  => '合同类别',
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => '合同金额（' . static::$unit . '）',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "签订日期" => text(['name' => 'signedDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "合同编号"   => text(array("name" => "orderNo")),
                    "合同名称"   => text(array("name" => "name")),
                ],
                [
                    '委外单位' => selectMultiple(['table' => 'supplier', 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'supplierId', 'where' => "coid = '" . self::$coid . "' and outsource = '是'"]),
                    '合同类别'  => select(["name" => "type",  'option' => ['主合同', '补充协议']]),
                    "状态" => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*委外合同入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=editPage')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= spanButton(['name' => '删除', 'page' => self::page, 'fun' => 'operate', 'para' => ['act' => 'del'], 'first' => true]);
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*委外合同列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'supplierId' => $this->post('supplierId'),
            'type' => $this->post('type'),
            'state' => $this->post('state'),
            'coid'=>self::$coid
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        // 查询自己
        if (!$this->power(self::page, "seeAll")) {
            $where .= " and stid = '" . self::$stid . "' ";
        }
        if ($this->post('signedDate')) {
            $where .= self::timeComparison($this->post('signedDate'), 'date', 'signedDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => "委外合同详情", "click" => "newIframe('委外合同详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
                "edit" => $array['state'] == '草稿' && $isEdit ? ["title" => "委外合同编辑", "click" => "newIframe('委外合同编辑','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $array['id'] . "')"] : [],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        if (empty($info['id'])) {
            return [];
        }
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => self::title,
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editPageEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => '',
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }
        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }


    public function editPage()
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        // 金额信息
        $moneyTr[] = ['', '计划回款日期', '计划回款金额（' . static::$unit . '）', '阶段', '备注'];
        $type = 'payback';
        $result = find(array(
            'field' => "id,date,money,stage,text",
            'table' => self::tablePay." where orderId = '{$info['id']}' order by time DESC"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['money'] = $array['money'] ? self::lostZero($array['money'], 'amount') : '';
                $array = (new salesContractClass())->prefixArrayKeys($array,$type);
                $array['list'] = $k+1;
                $moneyTr[] = $this->paybackRow($array);
            }
        }else{
            $moneyTr[] = $this->paybackRow([$type.'id'=>self::getId(), 'list'=>1]);
        }
        //按钮
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "EditPageForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            "post" => ["id" => $this->get('id')],
        ];
        $button[] = [
            "name" => '保存并提交',
            "type" => "弹出层",
            "cla" => $this->get('cla'),
            "fun" => "saveAndCommit",
            'style' => 'li-btn-blue-bg',
            "post" => "$('[name=" . self::page . "EditPageForm]').serialize()+'&act=start'",
        ];
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '合同编号' => text(['name' => "orderNo", 'class' => 'text', 'value' => $info['orderNo']]),
                    must . '合同名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    must . '委外单位' => selectMultiple(['table' => 'supplier', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'supplierId', 'where' => "state = '启用' and outsource = '是' and coid = '" . self::$coid . "'", 'value' => $info['supplierId'], 'class' => 'width250']),
                    must . '合同类别' => radio(['name' => "type", 'class' => 'text', 'checked' => $info['type'] ?: '主合同', 'value' => ['主合同', '补充协议']]),
                ],
                [
                    must . '签订日期' => text(['name' => "signedDate", 'class' => 'text', 'value' => $info['signedDate'], 'laydate' => []]),
                    '有效开始日期' => text(['name' => "startDate", 'class' => 'text', 'value' => $info['startDate'], 'laydate' => [],]),
                    '有效结束日期' => text(['name' => "endDate", 'class' => 'text', 'value' => $info['endDate'], 'laydate' => [],]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ],
            '金额信息' => [
                [
                    must . '合同金额' => text(['name' => "money", 'other' => self::digitalFiltering(), 'class' => 'text width350', 'value' => $info['money']]),
                    '结算方式' => radio(['name' => "payType", 'class' => 'text', 'checked' => $info['payType'], 'value' => ['预付', '现付', '月结'],]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'html' => $this->listTable(['tr' => $moneyTr, 'end' => true]),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);

        $data['html'] .= <<<EOT
        <script>
            //添加一行
            function addRow(e,type){
                $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                    $(e).closest('tr').after(res.data);
                    resetNumber($(e).closest('tbody'))
                },'json');
            }
        </script>
EOT;

        //返回
        return $this->tab($data);
    }

    /**
     * Desc : 回款计划明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function paybackRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $type = 'payback';
        $id = isset($data[$type.'id'])&&$data[$type.'id']?$data[$type.'id']:self::getId();
        $field = [$type.'date', $type.'money', $type.'stage', $type.'text'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'paybackRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'$type')"),
            hidden(['name' => $type . 'id[]', 'value' => $id]) .
            text(['name' => $type . 'date[]', 'laydate' => [], 'title' => '计划回款日期', 'value' => $array[$type.'date']]),
            text(['name' => $type . 'money[]', 'type' => 'text', 'other' => self::digitalFiltering(), 'title' => '计划回款金额（' . static::$unit . '）', 'value' => $array[$type.'money']]),
            select(['name' => $type . 'stage[]', 'title' => '阶段', 'option' => explode('，', para('salesContractStageOption')), 'value' => $array[$type.'stage']]),
            textarea(['name' => $type . 'text[]', 'title' => '备注', 'value' => $array[$type.'text']]),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $type = $this->post('type');
        switch ($type) {
            case 'payback':
                $res = json_decode($this->paybackRow(),true);
                $html = $res['html'];
                break;
            default:
                $html = '';
                break;
        }
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    /*基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
            'supplierId' => $this->post('supplierId'),
            'type' => $this->post('type'),
            'signedDate' => $this->post('signedDate'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('endDate'),
            'money' => $this->post('money')?self::formattingFigure($this->post('money')):'',
            'payType' => $this->post('payType'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'name' => '合同名称',
            'supplierId' => '委外单位',
            'type' => '类型',
            'signedDate' => '签订日期',
            'startDate' => '开始日期',
            'endDate' => '结束日期',
            'money' => '合同金额',
            'text' => '备注',
        ];
        $rules = [
            'orderNo' => 'required',
            'name' => 'required',
            'supplierId' => 'required',
            'type' => 'required',
            'signedDate' => 'required',
            'money' => 'required|numeric',
        ];

        // 合同回款
        $type = 'payback';
        $idArr = $this->post($type . 'id')?:[];
        $dateArr = $this->post($type . 'date');
        $moneyArr = $this->post($type . 'money');
        $stageArr = $this->post($type . 'stage');
        $textArr = $this->post($type . 'text');
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "orderNo = '$field[orderNo]' and coid = '" . self::$coid . "' and id !='$id'"))) {
            $json['warn'] = '已存在此编号的合同';
        } elseif (!empty($field['startDate']) && !empty($field['endDate']) && strtotime($field['endDate']) < strtotime($field['startDate'])) {
            $json['warn'] = '结束日期不能小于开始日期';
        } elseif($info['id'] && $info['state'] !='草稿'){
            $json['warn'] = '不是草稿状态，暂不能编辑';
        }else {
            // 开启事务
            $this->startTrans();

            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'state' => '草稿',
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (is_array($idArr)) {
                foreach ($idArr as $k => $nid) {
                    $mx = query(self::tablePay, "id = '$nid'");
                    if (empty($mx['id'])) {
                        $warn = static::insert(array(
                            'table' => self::tablePay,
                            'field' => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'date' => $dateArr[$k],
                                'money' => self::formattingFigure($moneyArr[$k]),
                                'stage' => $stageArr[$k],
                                'text' => $textArr[$k],
                            ]
                        ));
                    } else {
                        $warn = static::update(array(
                            'table' => self::tablePay,
                            'field' => [
                                'date' => $dateArr[$k],
                                'money' => self::formattingFigure($moneyArr[$k]),
                                'stage' => $stageArr[$k],
                                'text' => $textArr[$k],
                            ],
                            'where' => "id = '$nid'"
                        ));
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = '编辑付款明细失败';
                        break;
                    }
                }
                delete(['table' => self::tablePay, 'where' => " id NOT IN ('" . implode("','", $idArr) . "') AND orderId = '$id'  "]);
            }

            if (!in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 事务回滚
                $this->rollback();
            } else {
                // 提交事务
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . ($field['name'] ? "，合同名称【{$field['name']}】" : '');
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                $json['id'] = $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 保存并提交审批
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editPageEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            $id = $result['id'];
            $body = self::encryptDecrypt(json_encode([
                'name' => self::title,
                'table' => self::table,
                'process' => [
                    // 预览函数
                    'detail' => [
                        'cla' => $this->get('cla'),
                        'fun' => 'detail'
                    ],
                    // 保存函数
                    'save' => [
                        'cla' => $this->get('cla'),
                        'fun' => 'editPageEdit'
                    ],
                    //执行发起时验证函数
                    'before' => [
                        'cla' => $this->get('cla'),
                        'fun' => ''
                    ],
                    //完成发起后执行函数
                    'after' => [
                        'cla' => $this->get('cla'),
                        'fun' => ''
                    ],
                ],
                'href' => isset($result['href'])?$result['href']:'',
            ], 320));
            $res = auditClass::submitApprovalSignle($id,$body);
            if($res['warn'] == 1){
                return $res['data']; //自定义审批人
            }elseif($res['warn'] != 2){
                $_SESSION['warn'] = '提交失败，'.$res['warn'];
            }
        }
        return $resultJson;
    }


    /**
     * 详情页
     *
     * @return string
     */
    public function detail(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
                "menu" => [
                    "detail" => "基本信息",
                    "contractMx" => "合同明细",
                    'contractTrack' => '合同跟踪',
                    "file" => ["name" => "附件", "cla" => "file", "fun" => "outsourceContractFile"],
                ]
            ];
            //按钮
            $button = [];
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::page . "详情",
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
                    ];
                }
            }

            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            // 金额信息
            $moneyTr[] = ['计划回款日期', '计划回款金额（' . static::$unit . '）', '阶段', '备注'];
            $result = find(['table' => self::tablePay . " where orderId = '{$info['id']}' order by list"]);
            foreach ((array)$result['array'] as $array) {
                $moneyTr[] = [self::formatDate($array['date']), self::lostZero($array['money']), $array['stage'], $array['text']];
            }
            $moneyTab = $this->listTable(["tr" => $moneyTr, 'showSort' => true]);
            $supplier = query('supplier', "id = '$info[supplierId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                "基本信息" => [
                    [
                        "合同编号" => $info['orderNo'],
                        "合同名称" => $info['name'],
                        "委外单位" => $supplier['name'],
                        "合同类别" => $info['type'],
                    ],
                    [
                        "签订日期" => self::formatDate($info['signedDate']),
                        "有效开始日期" => self::formatDate($info['startDate']),
                        "有效结束日期" => self::formatDate($info['endDate']),
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
                "金额信息" => [
                    [
                        "合同金额(". static::$unit . ")" => self::lostZero($info['money']),
                        "结算方式" => $info['payType'],
                    ],
                ],

            ]);
            $data['html'] .= $this->detailList([
                'html' => $moneyTab,
            ]);
            $data['html']   .= $this->tableShow([
                "系统信息" => [
                    [
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => self::formatDate($info['time']),
                        "更新时间" => self::null($info['updateTime']),
                    ]
                ],
                "流程" => [
                    [
                        auditClass::auditRecord(self::table, $info['id'])
                    ]
                ],
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /*列表页-查询条件*/
    public function contractTrackOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "单据编号"   => text(array("name" => "orderNo")),
                    '委外单位' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    "物料名称" => text(["name" => "name"]),
                    "物料编码" => text(["name" => "code"]).
                        hidden(["name" => "orderId", 'value' => $this->get('id')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 合同跟踪
     */
    public function contractTrack(): bool|string
    {
        $html = $this->contractTrackOptions(false);
        $button = "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 合同跟踪
     */
    public function contractTrackSearch(): bool|string
    {
        $id = $this->post('orderId');
        //查询结果
        $where = " main.contractId = '$id'  ";
        //生成查询语句
        $where .= search([
            "like" => [
                'code' => $this->post('code'),
                'name' => $this->post('name'),
                'orderNo' => $this->post('orderNo'),
            ],
            "=" => [
                'main.supplierId' => $this->post('supplierId'),
                "main.state" => '已确认'
            ],
        ]);
        if ($this->post('createTime')) {
            $where .= self::timeComparison($this->post('createTime'), 'date', 'main.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.list',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            "table" => "outsource_process as main join outsource_process_material as a on main.id = a.orderId join material as b on a.materialId = b.id",
            'field' => "b.*,main.contractId,a.id as mxId,a.orderId,a.id,a.price,a.num,a.money,a.rate,a.text,main.recordDate,main.orderNo,main.supplierId",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $num = find(array(
                'table' => 'outsource_in_order as a join outsource_in_order_detail as b on a.id = b.orderId',
                'field' => "ifnull(sum(b.num),0) as num",
                'single' => "sourceId = '$array[mxId]' and state = '已确认'"
            ))['num'];
            $result = saleOrderClass::isTax($num, $array['price'], $array['rate']);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "contract":
                        $contract = query('outsource_contract', "id = '$array[contractId]'");
                        $row[] = $contract['orderNo'];
                        break;
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "num":
                        $row[] = self::lostZero($num, 'numPrecision');
                        break;
                    case "price":
                        $row[] = self::lostZero($array['price'], 'pricePrecision');
                        break;
                    case "rate":
                        $rate     = ($array['rate'] * 100) . '%';
                        $row[] = $rate;
                        break;
                    case "money":
                    case "taxMoney":
                    case "moneyWithTax":
                        $row[] = self::lostZero($result[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //控件
        $json['html'] = $page['hint'] . $button . "<form name='mxForm'>"  . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $tr = [];
        $sql = $_SESSION[self::page]['sql'];
        $title = ['单据日期', '单据编号', '合同编号',  '委外单位', '物料编码', '物料名称', '规格型号', '单位', '收货数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '税率(%)', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）'];
        $result = sqlFind($sql);
        if (is_array($result)) {
            foreach ($result as $array) {
                $num = find(array(
                    'table' => 'outsource_in_order as a join outsource_in_order_detail as b on a.id = b.orderId',
                    'field' => "ifnull(sum(b.num),0) as num",
                    'single' => "sourceId = '$array[mxId]' and state = '已确认'"
                ))['num'];
                $rate = ($array['rate'] * 100) . '%';
                $contract = query('outsource_contract', "id = '$array[contractId]'");
                $result = saleOrderClass::isTax($num, $array['price'], $array['rate']);
                $tr[] = [
                    $array['recordDate'],
                    $array['orderNo'],
                    $contract['orderNo'],
                    supplierClass::getName($array['supplierId']),
                    $array['code'],
                    $array['name'],
                    $array['model'],
                    $array['unit'],
                    self::lostZero($num,'numPrecision'),
                    self::lostZero($array['price'],'pricePrecision'),
                    self::lostZero($result['money']),
                    $rate,
                    self::lostZero($result['taxMoney']),
                    self::lostZero($result['moneyWithTax']),
                ];
            }
        }
        $text = $this->control['name'] . "导出了委外合同跟踪表";
        $this->logText(["type" => self::page, "text" => $text]);
        $this->excelOut($title, $tr, "委外合同跟踪表.xlsx");
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /*列表页-查询条件*/
    public function contractMxOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "产品编码" => text(array("name" => "code")),
                    "产品名称"   => text(array("name" => "name")),
                    "规格型号"   => text(array("name" => "model")).
                        hidden(["name" => "orderId", 'value' => $this->get('id')]),
                ],
                [
                    "工序" => text(array("name" => "process")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 合同明细
     * @return bool|string
     */
    public function contractMx()
    {
        $html = $this->contractMxOptions(false);
        $info = query(self::table, " id = '".$this->get('id')."' ");
        $button = '';
        if ($info['state'] == '草稿') {
            $button .= spanButton(['name' => '选择产品', 'page' => '' . $this->get('cla') . '', 'fun' => 'addMx', 'para' => ['id' => self::getId(), 'orderId' => $info['id'], 'callback' => self::page, 'tableMx' => self::tableMx]]);
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function contractMxSearch()
    {
        $id = $this->post('orderId');
        $info = query(self::table, " id = '$id' ");
        //查询结果
        $where = " orderId = '$id'   ";
        //生成查询语句
        $mwhere = search([
            "like" => [
                'code' => $this->post('code'),
                'name' => $this->post('name'),
                'model' => $this->post('model'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND materialId IN (SELECT `id` From `material` WHERE 1=1 $mwhere) ";
        }
        if($this->post('process')){
            $where .= " and processId in (select id from process where name like '%".$this->post('process')."%') ";
        }
        $page = $this->page([
            "table" => self::tableMx,
            "where" => $where,
            "order" => "`time` desc",
        ]);

        //获取表头
        $tr[] = ['', '产品编码', '产品名称', '规格型号', '单位', '工序', '数量', '加工单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '税率%', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '备注'];
        //获取记录
        foreach ($page['array'] as $k=>$array) {
            $material = query('material', " id = '{$array['materialId']}' ");
            if ($info['state'] == '草稿') {
                $num = text(['name' => 'num', 'other' => self::digitalFiltering('numPrecision'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width100', 'value' => self::lostZero($array['num'],'numPrecision'), 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '数量']);
                $price = text(['name' => 'price', 'other' => self::digitalFiltering('pricePrecision'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width100', 'value' => self::lostZero($array['price'],'pricePrecision'), 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '价格']);
                $rate = select(['name' => 'rate', 'title' => '税率', 'value' => $array['rate'] * 100, 'class' => 'select width100', 'option' => explode('，', para('taxRate')), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'change' => "textUpdate, {$this->get('cla')}, updateMx",]);
                $text = text(['name' => 'text', 'other' => self::digitalFiltering(), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'class' => 'text width200', 'value' => $array['text'], 'blur' => "textUpdate, {$this->get('cla')}, updateMx", 'title' => '备注']);
                $unit = select(array('name' => 'unit', 'value' => $array['unit'], 'class' => 'select width100', 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'title' => '单位', 'change' => "textUpdate, {$this->get('cla')}, updateMx", 'option' => machiningOrderClass::unitOption($array['materialId'])));
                $process = selectMultiple(array('name' => 'processId', 'class' => 'select width150', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'change' => "processUpdate", 'other' => " data-id='{$array['id']}' data-orderid='{$info['id']}' ", 'value' => $array['processId']));
                $total = text(array('name' => 'money', 'type' => 'text', 'other' => self::digitalFiltering('amount'), 'data' => ['id' => $array['id'], 'orderId' => $info['id']], 'blur' => "calculatePrice(this);textUpdate, {$this->get('cla')}, updateMx", 'class' => 'text width100', 'value' => self::lostZero($array['money'])));
            } else {
                $num = self::lostZero($array['num'],'numPrecision');
                $price = self::lostZero($array['price'],'pricePrecision');
                $rate = ($array['rate'] * 100) . '%';
                $text = $array['text'];
                $total = self::formattingFigure($array['money']);
                $unit = $array['unit'];
                $process = query("process"," id = '$array[processId]' ","name")['name'];
            }
            $money = self::formattingFigure($array['moneyWithOutTax']);
            $rateTotal = self::formattingFigure($array['taxMoney']);

            $list = ((int)$page['para']['pageNow'] - 1) * (int)$page['para']['pageNum'] + $k + 1;
            $operate = "<div class='list-number'>{$list}</div>";
            $operate .= $info['state'] == '草稿' ? spanButton(['name' => ' ', 'style' => 'delete-ico', 'page' => '' . $this->get('cla') . '', 'fun' => 'deleteMx', 'para' => ['id' => $array['id'], 'orderId' => $info['id'],], 'first' => true]) : '';
            $tr[] = [
                "<div class='list-edit-toolbar'>$operate</div>",
                $material['code'], $material['name'],  $material['model'], $unit, $process, $num, $price, "<span class='noTaxMoney'>{$money}</span>", $rate, "<span class='taxMoney'>{$rateTotal}</span>",$total,  $text];
        }
        //控件
        $json['html'] =
            "<form name='contractMxForm'>" .
                $this->tableMany(array("tr" => $tr, "page" => $page['para'])) .
            "</form>" .
            salesContractClass::updateJs() .
            $page['button'];
        $json['html'] .= <<<eof
<style>
    .fs-wrap{
        background-color: transparent;
        vertical-align: sub;
    }
</style>
<script>
// 工序文本框更新
function processUpdate(obj) {
    let cla = 'outsourceContract'
    let fun = 'updateMx'
    let field = $(obj).attr('name'), val = $(obj).val()
    if (field.length > 0 && val.length > 0) {
        const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
        let params = { id: $(obj).data('id'), orderid: $(obj).data('orderid') }
        params[field] = val
        $.post(url, params, function (resp) {
            if (resp.warn === 2) {
                if (resp.href) {
                    window.location.href = resp.href;
                } else {
                    msg(resp.msg)
                }
            } else {
                warn(resp.warn)
            }
        }, "json");
    }
}
</script>
eof;
        return json_encode($json, 320);
    }

    /**
     * 添加产品
     * @return bool|string
     */
    public function addMx()
    {
        $id    = $this->post('orderId');
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 0;
        $data             = [
            'sub'            => " onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "id", "value" => $id]) .
                hidden(["name" => "supplyControl", "value" => '允许委外']) .
                hidden(["name" => "attach", "value" => base64_encode(" and id NOT IN (SELECT materialId FROM " . self::tableMx . " WHERE  orderId = '{$id}'  ) ")]),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     * 添加
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info = query(self::table, " id = '{$id}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择记录';
        } else {
            $x = 0;
            $text = '';
            foreach ($mxIdArr as $mxId) {
                $material = query('material', " id = '$mxId'");
                $mxWhere = " materialId = '$mxId' and orderId = '$id'";
                $mx = query(self::tableMx, $mxWhere);
                if (empty($mx['id'])) {
                    //未在明细中
                    $warn = insert([
                        'table' => self::tableMx,
                        'field' => [
                            'id' => self::getId(),
                            'coid' => self::$coid,
                            'orderId' => $id,
                            'materialId' => $material['id'],
                            'unit' => $material['unit']
                        ]
                    ]);
                    if (in_array($warn, ['新增成功', '更新成功'])) {
                        $x++;
                        $text .= $this->control['name'] . "添加了产品【{$material['name']}】到" . self::title . "【{$info['orderNo']}】中<br>";
                    }
                } else {
                    $text .= $this->control['name'] . "添加产品【{$material['name']}】到" . self::title . "【{$info['orderNo']}】中失败：已存在此产品<br>";
                }

            }
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $json['href'] = $this->root . "control/adIndex.html?cla=" . self::page . "&fun=detail&menu=contractMx&id=" . $id;
            $_SESSION['warn'] = '添加了' . $x . '条产品到' . self::title;
        }
        return json_encode($json, 320);
    }

    public function deleteMx()
    {
        // 条件字段
        $wField = [
            'id' => $this->post('id'),
            'orderId' => $this->post('orderId'),
        ];
        $info = query(self::table, " id = '{$wField['orderId']}' ");
        $state = '草稿';
        if ($info['state'] != $state) {
            $json['warn'] = self::title . '非' . $state . '状态，无法删除';
        } else {
            $warn = delete([
                'table' => self::tableMx,
                'where' => generateWhere($wField),
            ]);
            $json['warn'] = ($warn == '删除成功') ? 2 : $warn;
            $json['href'] = root . 'control/adIndex.html?cla='.self::page.'&fun=detail&id=' . $wField['orderId'] . '&menu=contractMx';
        }
        return json_encode($json, 320);
    }

    public function updateMx()
    {
        // 条件字段
        $wField = [
            'id' => $this->post('id'),
            'orderId' => $this->post('orderid'),
        ];
        // 更新字段
        $field = [
            'unit' => $this->post('unit'),
            'processId' => $this->post('processId'),
            'aliasNo' => $this->post('aliasNo'),
            'aliasName' => $this->post('aliasName'),
            'num' => $this->post('num'),
            'price' => $this->post('price'),
            'rate' => $this->post('rate') ? (float)$this->post('rate') / 100 : '',
            'text' => $this->post('text'),
        ];
        $info = query(self::table, " id = '{$wField['orderId']}' ");
        $state = '草稿';
        if ($info['state'] != $state) {
            $json['warn'] = self::title . '申请单非' . $state . '状态，无法修改';
        /*} elseif (static::total(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and materialId = '$info[materialId]'")) > 0) {
            $json['warn'] = '已存在相同属性的产品';*/
        } else {
            $where = generateWhere($wField);
            $mx = query(self::tableMx, $where);
            if ($field['num'] || $field['price'] || $field['rate'] || $this->post('money')) {
                if ($this->post('money')) {
                    $taxMoney = self::formattingFigure($this->post('money') / (1 + $mx['rate']) * $mx['rate']);//税额
                    $field['price'] = self::formattingFigure(($this->post('money') - $taxMoney) / $mx['num']);
                }
                $result = saleOrderClass::isTax($field['num'] ?: $mx['num'], $field['price'] ?: $mx['price'], $field['rate'] ?: $mx['rate']);
                $field['taxMoney'] = $result['taxMoney'];
                $field['moneyWithOutTax'] = $result['money'];
                $field['money'] = $this->post('money') ?: $result['moneyWithTax'];
            }
            $json['warn']  = static::update([
                'table' => self::tableMx,
                'field' => $field,
                'where' => $where,
            ], false);
            if ($json['warn']=='更新成功'){
                $json['warn'] = 2;
                $json['msg'] = '更新成功';
            }
        }
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        $append = [];
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm,listForm,contractForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '草稿';

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if ($info[$fieldKey] !== $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】非{$fieldVlaue}状态，无法删除<br>";
                        continue;
                    }
                    // 删除相关 附件
                    $result = self::sqlFind("SELECT id, src FROM `attachFile` WHERE targetId = '{$info['id']}' ");
                    foreach ($result as $key => $attachFile) {
                        delete([
                            'table' => 'attachFile',
                            'where' => " id = '{$attachFile['id']}'",
                        ]);
                        fileDelete($attachFile['src']);
                    }
                    // 删除子表
                    delete([
                        "table" => self::tablePay,
                        "where" => " orderId = '$id' "
                    ]);
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" ."，名称【{$info['name']}】". '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条" . self::title;
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
